import { defineStore } from 'pinia';
import { ref, computed } from 'vue';

// 模拟新闻数据 - 包含最新新闻和热点新闻
const generateNewsData = () => {
  const categories = [
    '推荐', '综合', '娱乐', '社区', '购物', 
    '财经', '日报', '游戏', '体育', '影视', 
    '阅读', '应用', '开发', '安全'
  ];
  
  const platforms = [
    { name: '微博', hotIcon: '🔥' },
    { name: '知乎', hotIcon: '💡' },
    { name: '百度', hotIcon: '🔍' },
    { name: '头条', hotIcon: '📰' },
    { name: '腾讯', hotIcon: '🦁' },
    { name: '网易', hotIcon: '🐯' }
  ];
  
  const news = [];
  let id = 1;
  
  // 生成热点新闻
  for (let i = 0; i < 15; i++) {
    const category = categories[Math.floor(Math.random() * categories.length)];
    const platform = platforms[Math.floor(Math.random() * platforms.length)];
    const isHot = true;
    
    news.push({
      id: id++,
      title: `${platform.hotIcon}${platform.name}热搜：${category}领域重大突破引发热议`,
      source: platform.name,
      url: `https://${platform.name}.com/hot/${id}`,
      image: `https://picsum.photos/400/400?random=${id}&hot`,
      time: '刚刚',
      summary: `这是${category}领域的重大突破，引发${platform.name}平台用户广泛讨论，相关话题阅读量已超千万。`,
      category,
      hotValue: Math.floor(Math.random() * 1000000) + 500000,
      isHot,
      isNew: false
    });
  }
  
  // 生成最新新闻
  for (let i = 0; i < 30; i++) {
    const category = categories[Math.floor(Math.random() * categories.length)];
    const platform = platforms[Math.floor(Math.random() * platforms.length)];
    const isNew = true;
    const minutesAgo = Math.floor(Math.random() * 60);
    
    news.push({
      id: id++,
      title: `最新：${category}领域${platform.name}报道重要进展`,
      source: platform.name,
      url: `https://${platform.name}.com/news/${id}`,
      image: `https://picsum.photos/400/400?random=${id}&new`,
      time: `${minutesAgo}分钟前`,
      summary: `这是${category}领域的最新进展报道，详情请点击查看全文。专家表示，这一进展将带来深远影响。`,
      category,
      hotValue: Math.floor(Math.random() * 500000),
      isHot: false,
      isNew
    });
  }
  
  return news;
};

export const useNewsStore = defineStore('news', () => {
  // 状态对象
  const state = ref({
    newsData: [],
    favorites: JSON.parse(localStorage.getItem('newsFavorites') || '[]'),
    currentCategory: '推荐',
    isLoading: false,
    lastUpdated: null
  });
  
  // 分类列表
  const categories = ref([
    { id: '推荐', name: '推荐', icon: 'icon-recommend' },
    { id: '综合', name: '综合', icon: 'icon-general' },
    { id: '娱乐', name: '娱乐', icon: 'icon-entertainment' },
    { id: '社区', name: '社区', icon: 'icon-community' },
    { id: '购物', name: '购物', icon: 'icon-shopping' },
    { id: '财经', name: '财经', icon: 'icon-finance' },
    { id: '日报', name: '日报', icon: 'icon-daily' },
    { id: '游戏', name: '游戏', icon: 'icon-game' },
    { id: '体育', name: '体育', icon: 'icon-sports' },
    { id: '影视', name: '影视', icon: 'icon-movie' },
    { id: '阅读', name: '阅读', icon: 'icon-reading' },
    { id: '应用', name: '应用', icon: 'icon-app' },
    { id: '开发', name: '开发', icon: 'icon-dev' },
    { id: '安全', name: '安全', icon: 'icon-security' }
  ]);
  
  // 热点新闻
  const hotNews = computed(() => {
    return state.value.newsData
      .filter(item => item.isHot)
      .sort((a, b) => b.hotValue - a.hotValue)
      .slice(0, 6);
  });
  
  // 最新新闻
  const latestNews = computed(() => {
    return state.value.newsData
      .filter(item => item.isNew)
      .sort((a, b) => b.id - a.id)
      .slice(0, 10);
  });
  
  // 当前分类的新闻
  const categoryNews = computed(() => {
    return state.value.newsData.filter(
      item => item.category === state.value.currentCategory
    );
  });
  
  // 加载新闻数据
  const loadNews = async (category = '推荐') => {
    try {
      state.value.isLoading = true;
      state.value.currentCategory = category;
      
      // 模拟API请求延迟
      await new Promise(resolve => setTimeout(resolve, 800));
      
      // 生成模拟数据
      const news = generateNewsData();
      state.value.newsData = news;
      state.value.lastUpdated = new Date().toISOString();
      
      return true;
    } catch (error) {
      console.error('加载新闻失败:', error);
      return false;
    } finally {
      state.value.isLoading = false;
    }
  };
  
  // 切换收藏状态
  const toggleFavorite = (id) => {
    const index = state.value.favorites.indexOf(id);
    if (index === -1) {
      state.value.favorites.push(id);
    } else {
      state.value.favorites.splice(index, 1);
    }
    localStorage.setItem('newsFavorites', JSON.stringify(state.value.favorites));
  };
  
  // 检查是否收藏
  const isFavorite = (id) => {
    return state.value.favorites.includes(id);
  };
  
  // 获取收藏的新闻
  const favoriteNews = computed(() => {
    return state.value.newsData.filter(item => 
      state.value.favorites.includes(item.id)
    );
  });
  
  // 初始化
  loadNews();
  
  // 定时刷新新闻
  setInterval(() => {
    const hotCount = Math.floor(Math.random() * 3) + 1;
    const newCount = Math.floor(Math.random() * 5) + 2;
    
    // 模拟新闻更新
    const updatedNews = [...state.value.newsData];
    
    // 添加新热点
    for (let i = 0; i < hotCount; i++) {
      const category = categories.value[Math.floor(Math.random() * categories.value.length)].id;
      const platform = { name: '微博', hotIcon: '🔥' };
      
      updatedNews.unshift({
        id: Date.now() + i,
        title: `🔥新热点：${category}领域突发新闻引关注`,
        source: platform.name,
        url: `https://${platform.name}.com/hot/${Date.now() + i}`,
        image: `https://picsum.photos/400/400?random=${Date.now() + i}&hot`,
        time: '刚刚',
        summary: `这是${category}领域的最新热点事件，引发了广泛关注和讨论。`,
        category,
        hotValue: Math.floor(Math.random() * 1000000) + 800000,
        isHot: true,
        isNew: false
      });
    }
    
    // 添加新新闻
    for (let i = 0; i < newCount; i++) {
      const category = categories.value[Math.floor(Math.random() * categories.value.length)].id;
      const platform = { name: '腾讯', hotIcon: '🦁' };
      
      updatedNews.unshift({
        id: Date.now() + 1000 + i,
        title: `最新：${category}领域报道重要进展`,
        source: platform.name,
        url: `https://${platform.name}.com/news/${Date.now() + 1000 + i}`,
        image: `https://picsum.photos/400/400?random=${Date.now() + 1000 + i}&new`,
        time: '刚刚',
        summary: `这是${category}领域的最新进展报道，详情请点击查看全文。`,
        category,
        hotValue: Math.floor(Math.random() * 300000),
        isHot: false,
        isNew: true
      });
    }
    
    // 更新状态
    state.value.newsData = updatedNews.slice(0, 100); // 保留最新100条
    state.value.lastUpdated = new Date().toISOString();
  }, 30000); // 每30秒更新一次
  
  return {
    state,
    categories,
    hotNews,
    latestNews,
    categoryNews,
    favoriteNews,
    loadNews,
    toggleFavorite,
    isFavorite
  };
});